package cn.tedu.sp06.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.web.util.JsonResult;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@Slf4j
public class RibbonController {
    @Autowired
    private RestTemplate rt;
    @HystrixCommand(fallbackMethod = "getItemsFB")
    @GetMapping("/item-service/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId){
        //RestTemplate必须给出具体的服务器地址
        //Ribbon 对 RestTemplate 进行了增强(通过AOP),提供负载均衡的功能
        //根据注册表注册的主机地址列表,做负载均衡访问
        return rt.getForObject("http://item-service/{1}", JsonResult.class,orderId);
    }

    @HystrixCommand(fallbackMethod = "decreaseNumberFB")
    @PostMapping("/item-service/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
        f.setReadTimeout(1000);
        return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
    }

    /**
     * eureka的注册表
     * item-service  ---localhost:8001,localhost:8002
     * */


    public JsonResult<List<Item>> getItemsFB(String orderId){
        //上面的方法中,调用远程服务失败,执行这里的降级代码,直接向客户端返回响应
        return JsonResult.err().msg("商品调用服务失败");
    }


    public JsonResult<?> decreaseNumberFB(List<Item> items){
        return JsonResult.err().msg("商品调用服务失败");
    }

}
